/**
 * @projectName gs_online
 * @package com.answer.wx.gateway.service.impl
 * @className com.answer.wx.gateway.service.impl.MessageServiceImpl
 */
package com.answer.wx.gateway.service.impl;

import com.answer.wx.common.enums.ErrorEnum;
import com.answer.wx.common.exception.RequestException;
import com.answer.wx.common.response.ResponseListEntity;
import com.answer.wx.common.utils.DateUtils;
import com.answer.wx.dao.custom.mapper.CustomMessageMapper;
import com.answer.wx.dao.custom.mapper.CustomNewMessageMapper;
import com.answer.wx.dao.mapper.*;
import com.answer.wx.dao.model.*;
import com.answer.wx.gateway.bean.CommentBean;
import com.answer.wx.gateway.bean.MessageBean;
import com.answer.wx.gateway.bean.NewMessageBean;
import com.answer.wx.gateway.bean.ShopBean;
import com.answer.wx.gateway.service.MessageService;
import com.answer.wx.gateway.service.NewsService;
import com.answer.wx.gateway.service.UserService;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

import static com.github.pagehelper.PageInfo.of;

/**
 * MessageServiceImpl
 * @description message实现类
 * @author answer_wx
 * @date 2022/8/8 12:44
 * @version 1.0
 */
@Service
@Slf4j
public class MessageServiceImpl implements MessageService {
    @Autowired
    private NewsService newsService;
    @Autowired
    private MessageMapper messageMapper;
    @Autowired
    private NewMessageMapper newMessageMapper;
    @Autowired
    private MessageImageMapper messageImageMapper;
    @Autowired
    private AttendMapper attendMapper;
    @Autowired
    private CustomNewMessageMapper customNewMessageMapper;
    @Autowired
    private CustomMessageMapper customMessageMapper;
    @Autowired
    private CollectMapper collectMapper;
    @Autowired
    private CommentMapper commentMapper;
    @Autowired
    private CommentReplyMapper commentReplyMapper;
    @Autowired
    private ShopMapper shopMapper;
    @Autowired
    private ShopImageMapper shopImageMapper;
    @Autowired
    private ShopBusinessMapper shopBusinessMapper;
    @Autowired
    private UserService userService;

    @Transactional
    @Override
    public MessageBean getMessageDetailById(Integer messageId) {
        Message message = messageMapper.selectByPrimaryKey(messageId);
        if (message == null) {
            return null;
        }
        MessageBean messageBean = new MessageBean();
        BeanUtils.copyProperties(message, messageBean);

        messageBean.setCreateTime(DateUtils.format(message.getMessageCreatTime()));
        Comment comment = new Comment();
        comment.setMessageId(messageId);
        List<Comment> comments = commentMapper.select(comment);
        User user = userService.getById(message.getUserId());
        messageBean.setUser(user);
        MessageImage messageImage = new MessageImage();
        messageImage.setMessageId(messageId);
        messageBean.setMessageImage(messageImageMapper.select(messageImage));

        Integer messageWatch = messageBean.getMessageWatch();
        Message message1 = new Message();
        message1.setMessageId(messageId);
        message1.setMessageWatch(messageWatch + 1);
        message1.setMessageComment(comments.size());
        messageMapper.updateByPrimaryKeySelective(message1);

        if (comments.size() == 0) {
            return messageBean;
        }
        List<CommentBean> collect = comments.stream().map(comment1 -> {
            CommentBean commentBean = new CommentBean();
            BeanUtils.copyProperties(comment1, commentBean);
            commentBean.setCommentId(comment1.getCommentId());
            commentBean.setCreateTime(DateUtils.format(comment1.getCommentCreatTime()));
            CommentReply commentReply = new CommentReply();
            commentReply.setCommentId(comment1.getCommentId());
            commentBean.setCommentReplies(commentReplyMapper.select(commentReply));
            commentBean.setUser(userService.getById(comment1.getUserId()));
            return commentBean;
        }).collect(Collectors.toList());
        messageBean.setComments(collect);
        return messageBean;
    }

    @Override
    public List<MessageBean> getAllMessage(Integer userId) {
        Example example = new Example(Message.class);
        if (userId != null) {
            example.createCriteria().andEqualTo("userId", userId);
        }
        example.setOrderByClause("message_creat_time desc");
        return messageMapper.selectByExample(example).stream().map(message -> {
            MessageBean messageBean = new MessageBean();
            BeanUtils.copyProperties(message, messageBean);
            return messageBean;
        }).collect(Collectors.toList());
    }

    public List<Collect> getAllCollectionMessage(Integer userId) {
        Example example = new Example(Collect.class);
        if (userId != null) {
            example.createCriteria().andEqualTo("userId", userId);
        }
        example.setOrderByClause("collect_id desc");
        return collectMapper.selectByExample(example);
    }


    @Override
    public List<MessageBean> getAllMessageDetail(Integer pageNumber) {
        PageHelper.startPage(pageNumber, 8);
        PageInfo<MessageBean> pageInfo = new PageInfo<MessageBean>(getAllMessage(null));
        List<MessageBean> allMessage = pageInfo.getList();
        return getImage(allMessage);
    }

    @Override
    public List<MessageImage> findList(MessageImage image) {
        Example example = new Example(MessageImage.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("messageId", image.getMessageId());
        return messageImageMapper.selectByExample(example);
    }

    @Override
    public List<Message> getLost() {
        Example example = new Example(Message.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("categoryId", 1);
        example.setOrderByClause("message_creat_time desc");
        return messageMapper.selectByExample(example);
    }

    @Override
    public NewMessage getLastNewMessage(Integer userId) {
        return customNewMessageMapper.getLastNewMessage(userId);
    }

    @Override
    @Transactional
    public MessageBean addMessage(MessageBean message) {
        User user = userService.getById(message.getUserId());
        if (user == null) {
            throw new RequestException(ErrorEnum.ACCOUNT_EXPIRE, "用户不存在");
        }
        if (user.getUserAllow() != 1) {
            throw new RequestException(ErrorEnum.OPERATION_FAIL, "无权操作");
        }
        List<String> resultImages = message.getResultImage();
        messageMapper.insertSelective(message);
        for (int i = 0; i < resultImages.size(); i++) {
            MessageImage messageImage = new MessageImage();
            messageImage.setImageUrl(resultImages.get(i));
            messageImage.setMessageId(message.getMessageId());
            messageImageMapper.insertSelective(messageImage);
        }
        return message;
    }

    @Override
    public List<MessageBean> getImage(List<MessageBean> allMessage) {
        for (int i = 0; i < allMessage.size(); i++) {
            allMessage.get(i).setUser(userService.getById(allMessage.get(i).getUserId()));
            MessageImage messageImage = new MessageImage();
            messageImage.setMessageId(allMessage.get(i).getMessageId());
            allMessage.get(i).setMessageImage(findList(messageImage));
        }
        return allMessage;
    }

    @Override
    public List<MessageBean> getMessageByCategoryAndKeyword(Integer categoryId, String keywork) {
        Example example = new Example(Message.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("categoryId", categoryId);
        criteria.andLike("messageDetail", "%" + keywork + "%");
        example.setOrderByClause("message_creat_time desc");
        return messageMapper.selectByExample(example).stream().map(message -> {
            MessageBean bean = new MessageBean();
            BeanUtils.copyProperties(message, bean);
            return bean;
        }).collect(Collectors.toList());
    }

    public List<MessageBean> getMessageByCategoryId(Integer categoryId) {
        Example example = new Example(Message.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("categoryId", categoryId);
        example.setOrderByClause("message_creat_time desc");
        return messageMapper.selectByExample(example).stream().map(message -> {
            MessageBean bean = new MessageBean();
            BeanUtils.copyProperties(message, bean);
            return bean;
        }).collect(Collectors.toList());
    }

    @Override
    public ResponseListEntity<MessageBean> getMessageByCategoryId(Integer categoryId, Integer pageNumber) {
        ResponseListEntity<MessageBean> entity = ResponseListEntity.newInstance();
        Page<MessageBean> page = PageHelper.startPage(pageNumber, 8);
        PageInfo<MessageBean> pageInfo = new PageInfo<MessageBean>(getMessageByCategoryId(categoryId));
        if (pageNumber >= page.getPages()) {
            entity.setHasNext(false);
        }
        entity.setList(getImage(pageInfo.getList()));
        return entity;
    }

    @Override
    public List<Attend> getAllAttendMessageByUserId(Integer userId) {
        Example example = new Example(Attend.class);
        example.createCriteria().andEqualTo("userId", userId);
        example.setOrderByClause("attend_id desc");
        return attendMapper.selectByExample(example);
    }

    @Override
    public ResponseListEntity<MessageBean> getAttendMessageByUserId(Integer userId, Integer pageNumber) {
        ResponseListEntity<MessageBean> entity = ResponseListEntity.newInstance();
        Page page = PageHelper.startPage(pageNumber, 5);
        PageInfo<Attend> pageInfo = new PageInfo<Attend>(getAllAttendMessageByUserId(userId));
        List<Attend> list = pageInfo.getList();

        List<MessageBean> list1 = new ArrayList<MessageBean>();
        for (int i = 0; i < list.size(); i++) {
            Integer messageId = list.get(i).getMessageId();
            Message message = messageMapper.selectByPrimaryKey(messageId);
            MessageBean bean = new MessageBean();
            BeanUtils.copyProperties(message, bean);
            list1.add(bean);
        }
        if (pageNumber >= page.getPages()) {
            entity.setHasNext(false);
        }
        entity.setList(getImage(list1));
        return entity;
    }

    @Override
    public void updateMessageByUserId(Integer userId, Integer messageId, String message) {
        User user = userService.getById(userId);
        if (user == null) {
            throw new RequestException(ErrorEnum.ACCOUNT_EXPIRE, "用户不存在！");
        }
        Message message1 = new Message();
        message1.setMessageId(messageId);
        if (user.getUserIsAdmin() != 2) {
            message1.setMessageId(messageId);
            message1.setUserId(userId);
            int count = messageMapper.selectCount(message1);
            if (count == 0) {
                throw new RequestException(ErrorEnum.OPERATION_FAIL, "操作失败！");
            }
        }
        message1.setMessageDetail(message);
        messageMapper.updateByPrimaryKeySelective(message1);
    }

    @Override
    public ResponseListEntity<MessageImage> deleteMessage(Integer userId, Integer messageId) {
        ResponseListEntity<MessageImage> entity = ResponseListEntity.newInstance();
        User user = userService.getById(userId);
        if (user == null) {
            throw new RequestException(ErrorEnum.ACCOUNT_EXPIRE, "账户不存在!");
        }
        Message message = messageMapper.selectByPrimaryKey(messageId);
        if (user.getUserIsAdmin() == 2 || message.getUserId().equals(user.getUserId())) {
            // 删除评论
            customMessageMapper.deleteCommentAndReply(messageId);
            /**
             *  我参与的
             */
            Attend attend = new Attend();
            attend.setMessageId(messageId);
            attendMapper.delete(attend);
            /**
             * 删除收藏
             */
            Collect collect = new Collect();
            collect.setMessageId(messageId);
            collectMapper.delete(collect);

            /**
             * 删除消息
             */
            NewMessage newMessage = new NewMessage();
            newMessage.setMessageId(messageId);
            newMessageMapper.delete(newMessage);

            messageMapper.deleteByPrimaryKey(messageId);
            MessageImage messageImage = new MessageImage();
            messageImage.setMessageId(messageId);
            List<MessageImage> images = findList(messageImage);
            messageImageMapper.delete(messageImage);
            entity.setList(images);
            return entity;
        }
        return null;
    }

    @Override
    public void addNewMessageByAdmin(Integer userId, Integer messageId, String newMessage) {
        User user = userService.getById(userId);
        if (user.getUserIsAdmin() != 2) {
            throw new RequestException(ErrorEnum.OPERATION_FAIL, "操作失败");
        }
        Message res = messageMapper.selectByPrimaryKey(messageId);
        NewMessage message = new NewMessage();
        message.setNewMessageDetail(newMessage);
        message.setMessageId(messageId);
        message.setUserId(res.getUserId());
        message.setNewMessageType(3);
        newMessageMapper.insertSelective(message);
    }

    @Override
    public Integer addShareCount(Integer messageId) {
        Message message = messageMapper.selectByPrimaryKey(messageId);
        message.setMessageShare(message.getMessageShare() + 1);
        messageMapper.updateByPrimaryKeySelective(message);
        return message.getMessageShare();
    }

    @Override
    public List<MessageBean> getMessageByKeyword(String keyword, Integer pageNumber) {
        PageHelper.startPage(pageNumber, 3);
        List<MessageBean> messageBeans = customMessageMapper.getMessageByKeyword(keyword).stream().map(message -> {
            MessageBean messageBean = new MessageBean();
            BeanUtils.copyProperties(message, messageBean);
            return messageBean;
        }).collect(Collectors.toList());
        PageInfo<MessageBean> pageInfo = new PageInfo<>(messageBeans);
        List<MessageBean> allMessage = pageInfo.getList();
        return getImage(allMessage);
    }

    @Override
    public ShopBean getShopMessageById(Integer id) {
        Shop shop = shopMapper.selectByPrimaryKey(id);
        ShopBean shopBean = new ShopBean();
        BeanUtils.copyProperties(shop, shopBean);
        shopBean.setCreateTime(DateUtils.format(shop.getShopCreatTime()));
        ShopImage shopImage = new ShopImage();
        shopImage.setShopId(id);
        shopBean.setShopImages(shopImageMapper.select(shopImage));
        ShopBusiness shopBusiness = new ShopBusiness();
        shopBusiness.setShopId(id);
        shopBean.setShopBusinesses(shopBusinessMapper.select(shopBusiness));
        return shopBean;
    }

    @Override
    public ResponseListEntity<MessageBean> getMessageDetailByUserId(Integer userId, Integer pageNumber) {
        ResponseListEntity<MessageBean> entity = ResponseListEntity.newInstance();
        User user = userService.getById(userId);
        PageInfo<MessageBean> pageInfo;
        Page<Object> page;
        if (user.getUserIsAdmin() == 2) {
            page = PageHelper.startPage(pageNumber, 5);
            pageInfo = PageInfo.of(getAllMessage(null));
        } else {
            page = PageHelper.startPage(pageNumber, 3);
            pageInfo = PageInfo.of(getAllMessage(userId));
        }
        if (pageNumber >= page.getPages()) {
            entity.setHasNext(false);
        }
        entity.setList(getImage(pageInfo.getList()));
        return entity;
    }

    @Override
    public ResponseListEntity<MessageBean> getAllCollectionMessageByUserId(Integer userId, Integer pageNumber) {
        ResponseListEntity<MessageBean> entity = ResponseListEntity.newInstance();
        User user = userService.getById(userId);
        if (user == null) {
            throw new RequestException(ErrorEnum.ACCOUNT_EXPIRE, "账户不存在!");
        }
        Page page = PageHelper.startPage(pageNumber, 5);
        PageInfo<Collect> pageInfo = new PageInfo<>(getAllCollectionMessage(userId));
        List<Collect> list = pageInfo.getList();
        List<MessageBean> res = new ArrayList<>();
        for (Collect collect : list) {
            Integer messageId = collect.getMessageId();
            Message message = messageMapper.selectByPrimaryKey(messageId);
            MessageBean messageBean = new MessageBean();
            messageBean.setUser(user);
            BeanUtils.copyProperties(message, messageBean);
            res.add(messageBean);
        }
        if (pageNumber >= page.getPages()) {
            entity.setHasNext(false);
        }
        entity.setList(res);
        return entity;
    }

    @Override
    public ResponseListEntity<NewMessageBean> getAllNewMessage(Integer userId, Integer pageNumber) {
        ResponseListEntity<NewMessageBean> entity = ResponseListEntity.newInstance();
        User user = userService.getById(userId);
        if (user == null) {
            return null;
        }
        Page page = PageHelper.startPage(pageNumber, 10);
        PageInfo<NewMessage> pageInfo = new PageInfo<>(customNewMessageMapper.getAllNewMessage(userId));
        if (pageNumber >= page.getPages()) {
            entity.setHasNext(false);
        }
        List<NewMessage> newMessages = pageInfo.getList();
        List<NewMessageBean> collect = newMessages.stream().map(newMessage -> {
            NewMessageBean newMessageBean = new NewMessageBean();
            BeanUtils.copyProperties(newMessage, newMessageBean);
            newMessageBean.setCreateTime(DateUtils.format(newMessage.getNewMessageTime()));
            return newMessageBean;
        }).collect(Collectors.toList());
        entity.setList(collect);
        return entity;
    }
}